package com.sky.service.impl;

import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Transactional // 涉及多张表，开启事务保证正确
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        log.info("开始插入");

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        log.info("拷贝属性");

        // 1. 向菜品表插入1条数据
        dishMapper.insert(dish);
        log.info("插入菜品执行成功");
        // 获取Insert语句生成的主键值
        Long dishId = dish.getId();
        // 2. 向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

}
